<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Muse","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="​         原文链接：https:&#x2F;&#x2F;blog.csdn.net&#x2F;wzy1935&#x2F;article&#x2F;details&#x2F;124622552 ​        我们已经知道了PySimpleGUI使用事件循环来处理GUI事件，这里，我们考虑怎么把我们的功能代码和显示代码分离，以及解决多线程问题。 事件循环我们用一个简单的例子来回顾一遍我们学过了什么。我们简单的来写一个计算器： 1234567891">
<meta property="og:type" content="article">
<meta property="og:title" content="pysimplegui事件逻辑">
<meta property="og:url" content="http://example.com/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/index.html">
<meta property="og:site_name" content="学无止境">
<meta property="og:description" content="​         原文链接：https:&#x2F;&#x2F;blog.csdn.net&#x2F;wzy1935&#x2F;article&#x2F;details&#x2F;124622552 ​        我们已经知道了PySimpleGUI使用事件循环来处理GUI事件，这里，我们考虑怎么把我们的功能代码和显示代码分离，以及解决多线程问题。 事件循环我们用一个简单的例子来回顾一遍我们学过了什么。我们简单的来写一个计算器： 1234567891">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201019426.png">
<meta property="og:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201027979.png">
<meta property="article:published_time" content="2024-01-20T02:15:19.000Z">
<meta property="article:modified_time" content="2024-01-20T02:15:19.000Z">
<meta property="article:author" content="xudonglei">
<meta property="article:tag" content="pysimplegui">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201019426.png">

<link rel="canonical" href="http://example.com/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>pysimplegui事件逻辑 | 学无止境</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">学无止境</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Do not bb, show me the example</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="xudonglei">
      <meta itemprop="description" content="搬砖 嵌入式">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="学无止境">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          pysimplegui事件逻辑
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2024-01-20 10:15:19" itemprop="dateCreated datePublished" datetime="2024-01-20T10:15:19+08:00">2024-01-20</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          
            <span id="/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/" class="post-meta-item leancloud_visitors" data-flag-title="pysimplegui事件逻辑" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2024/01/20/pysimplegui%E4%BA%8B%E4%BB%B6%E9%80%BB%E8%BE%91/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>​         原文链接：<a target="_blank" rel="noopener" href="https://blog.csdn.net/wzy1935/article/details/124622552">https://blog.csdn.net/wzy1935/article/details/124622552</a></p>
<p>​        我们已经知道了PySimpleGUI使用事件循环来处理GUI事件，这里，我们考虑怎么把我们的功能代码和显示代码分离，以及解决多线程问题。</p>
<h3 id="事件循环"><a href="#事件循环" class="headerlink" title="事件循环"></a>事件循环</h3><p>我们用一个简单的例子来回顾一遍我们学过了什么。我们简单的来写一个计算器：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"></span><br><span class="line">progress = sg.ProgressBar(<span class="number">100</span>)</span><br><span class="line">num1_inp = sg.Input(size=<span class="number">5</span>)</span><br><span class="line">num2_inp = sg.Input(size=<span class="number">5</span>)</span><br><span class="line">result_txt = sg.Text()</span><br><span class="line">add_btn = sg.Button(<span class="string">&#x27;add&#x27;</span>)</span><br><span class="line"></span><br><span class="line">layout = [</span><br><span class="line">    [num1_inp, num2_inp, result_txt],</span><br><span class="line">    [progress],</span><br><span class="line">    [add_btn]</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">window = sg.Window(<span class="string">&#x27;slow calculator&#x27;</span>, layout)</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;add&#x27;</span>:</span><br><span class="line">        num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">        num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">        result_txt.update(<span class="built_in">str</span>(num1 + num2))</span><br></pre></td></tr></table></figure>
<p>我们可以看到，确实可以正常运行：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201019426.png" style="zoom:80%;">

<p>但是很明显，这不是一个好的代码规范。我们把GUI代码和逻辑代码混写在一起，现在看起来代码还可以，等我们要实现的功能多了，代码可就要向“屎山”进化了。我们先把界面响应和功能实现分别抽离出来：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># omitted...</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span>(<span class="params">a, b</span>):</span></span><br><span class="line">    <span class="keyword">return</span> a + b</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_btn_click</span>():</span></span><br><span class="line">    num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">    num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">    result_txt.update(add(num1, num2))</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event == <span class="string">&#x27;add&#x27;</span>:</span><br><span class="line">        add_btn_click()</span><br></pre></td></tr></table></figure>
<p>​        我们这次把功能代码 add() 和界面触发 add_btn_click() 单独写成一个方法，这样GUI和功能实现就不会相互干扰，你就可以专注不同部分的代码编写了。这时，功能代码完全可以单独抽到一个文件里编写，再也不用看着GUI代码头疼了。当然，这里的代码还可以做的更好：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"><span class="keyword">import</span> api</span><br><span class="line"></span><br><span class="line"><span class="comment"># omitted...</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_btn_click</span>(<span class="params">value</span>):</span></span><br><span class="line">    num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">    num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">    result_txt.update(api.add(num1, num2))</span><br><span class="line"></span><br><span class="line">event_callbacks = &#123;</span><br><span class="line">    <span class="string">&#x27;add&#x27;</span>: add_btn_click</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event <span class="keyword">in</span> event_callbacks:</span><br><span class="line">        event_callbacks[event](value)</span><br></pre></td></tr></table></figure>
<p>​        这次，我们把功能代码单独放在了外部文件 api.py 里。并且，添加了一个event_callbacks的map，以后只需要管理这个map就好了！</p>
<h3 id="长时任务"><a href="#长时任务" class="headerlink" title="长时任务"></a>长时任务</h3><p>​        接下来的问题也是编写GUI头疼的一大难题：长时任务。当你的功能代码很耗时的时候，GUI就会直接卡在那里…看下面的代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span>(<span class="params">a, b</span>):</span></span><br><span class="line">    time.sleep(<span class="number">5</span>)</span><br><span class="line">    <span class="keyword">return</span> a + b</span><br></pre></td></tr></table></figure>
<p>假设我们的大聪明功能 add 非常耗时，算一次加法要5秒。按照之前的代码，界面就真的会卡住5秒…</p>
<p>​        一个常见的解决方案是多线程。这里需要注意的是， <strong>谨慎使用多线程！！</strong> 看官方的解释：</p>
<img src="https://xdl-blog-picture.oss-cn-shanghai.aliyuncs.com/img/202401201027979.png" style="zoom:80%;">

<p>当然了，这里的意思不是说不能用，只是说最好确保GUI线程是主线程。</p>
<h4 id="perform-long-operation（推荐）"><a href="#perform-long-operation（推荐）" class="headerlink" title="perform_long_operation（推荐）"></a>perform_long_operation（推荐）</h4><p>​        使用 window.perform_long_operation 可以更简单的解决问题。我们在事件循环里使用它。<strong>第一个参数是需要执行的函数，第二个参数是执行后需要触发的事件</strong>。对应函数的返回值会作为window.read()获得的value。和刚刚几乎一样的代码，只不过没有用多线程：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"><span class="keyword">import</span> api</span><br><span class="line"></span><br><span class="line"><span class="comment"># omitted...</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_btn_click</span>(<span class="params">value</span>):</span></span><br><span class="line">    num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">    num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">    window.perform_long_operation(<span class="keyword">lambda</span> :api.add(num1, num2), <span class="string">&#x27;add_output&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_output</span>(<span class="params">value</span>):</span></span><br><span class="line">    result_txt.update(<span class="built_in">str</span>(value[<span class="string">&#x27;add_output&#x27;</span>]))</span><br><span class="line"></span><br><span class="line">event_callbacks = &#123;</span><br><span class="line">    <span class="string">&#x27;add&#x27;</span>: add_btn_click,</span><br><span class="line">    <span class="string">&#x27;add_output&#x27;</span>: add_output</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event <span class="keyword">in</span> event_callbacks:</span><br><span class="line">        event_callbacks[event](value)</span><br></pre></td></tr></table></figure>
<p>​        这里注意，当需要让perform_long_operation触发带参方法时，需要使用lambda。直接按上文写法就好了。</p>
<h4 id="偷懒写法（不推荐）"><a href="#偷懒写法（不推荐）" class="headerlink" title="偷懒写法（不推荐）"></a>偷懒写法（不推荐）</h4><p>​        这里就直接把要更新的组件给传进新线程了，新线程里会直接调用组件的方法来修改值。下面的代码使用了perform_long_operation直接让add_btn_click在新进程里调用，这样连接收值的事件都不用了，直接在新线程里修改result_txt。当然不推荐这种写法，虽然我在测试里是可以这样成功运行，但官方貌似没有这种示例，所以可能有bug。这次是完整的代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> PySimpleGUI <span class="keyword">as</span> sg</span><br><span class="line"><span class="keyword">import</span> api</span><br><span class="line"></span><br><span class="line">progress = sg.ProgressBar(<span class="number">100</span>)</span><br><span class="line">num1_inp = sg.Input(size=<span class="number">5</span>)</span><br><span class="line">num2_inp = sg.Input(size=<span class="number">5</span>)</span><br><span class="line">result_txt = sg.Text()</span><br><span class="line">add_btn = sg.Button(<span class="string">&#x27;add&#x27;</span>)</span><br><span class="line"></span><br><span class="line">layout = [</span><br><span class="line">    [num1_inp, num2_inp, result_txt],</span><br><span class="line">    [progress],</span><br><span class="line">    [add_btn]</span><br><span class="line">]</span><br><span class="line"></span><br><span class="line">window = sg.Window(<span class="string">&#x27;slow calculator&#x27;</span>, layout)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_btn_click</span>(<span class="params">value</span>):</span> <span class="comment"># multi-thread this method directly</span></span><br><span class="line">    num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">    num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">    output = api.add(num1, num2)</span><br><span class="line">    result_txt.update(<span class="built_in">str</span>(output))</span><br><span class="line"></span><br><span class="line">event_callbacks = &#123;</span><br><span class="line">    <span class="string">&#x27;add&#x27;</span>: add_btn_click</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> <span class="literal">True</span>:</span><br><span class="line">    event, value = window.read()</span><br><span class="line">    <span class="keyword">if</span> event == sg.WINDOW_CLOSED: <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">if</span> event <span class="keyword">in</span> event_callbacks:</span><br><span class="line">        window.perform_long_operation(<span class="keyword">lambda</span> :event_callbacks[event](value), <span class="string">&#x27;&#x27;</span>)</span><br></pre></td></tr></table></figure>
<p>不过确实很方便就是了，目前我也没碰着过bug，写写代码自用应该没有什么问题。</p>
<h3 id="进度条"><a href="#进度条" class="headerlink" title="进度条"></a>进度条</h3><p>​        最后以一个常见需求结束吧。进度条需要功能代码运行时实时提醒界面更新进度条的值。可以用write_event_value实现，也可以偷懒直接把进度条组件作为入参修改值。这里还是用偷懒写法了（因为真的懒…），所以直接在偷懒写法的版本上做修改了。</p>
<p>​        修改add方法，现在add时同时更新进度条：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add</span>(<span class="params">a, b, progress_bar</span>):</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">100</span>):</span><br><span class="line">        time.sleep(<span class="number">0.05</span>)</span><br><span class="line">        progress_bar.update(i+<span class="number">1</span>)</span><br><span class="line">    <span class="keyword">return</span> a+b</span><br></pre></td></tr></table></figure>
<p>​        把进组条组件传进去：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">add_btn_click</span>(<span class="params">value</span>):</span></span><br><span class="line">    num1 = <span class="built_in">int</span>(num1_inp.get())</span><br><span class="line">    num2 = <span class="built_in">int</span>(num2_inp.get())</span><br><span class="line">    output = api.add(num1, num2, progress)</span><br><span class="line">    result_txt.update(<span class="built_in">str</span>(output))</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/pysimplegui/" rel="tag"># pysimplegui</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2024/01/20/pysimplegui%E7%BB%84%E4%BB%B6%E4%B8%8E%E5%B8%83%E5%B1%80/" rel="prev" title="pysimplegui组件与布局">
      <i class="fa fa-chevron-left"></i> pysimplegui组件与布局
    </a></div>
      <div class="post-nav-item">
    <a href="/2024/01/20/pysimplegui%E9%AB%98%E7%BA%A7%E5%92%8C%E8%87%AA%E5%AE%9A%E4%B9%89%E4%BA%8B%E4%BB%B6/" rel="next" title="pysimplegui高级和自定义事件">
      pysimplegui高级和自定义事件 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8B%E4%BB%B6%E5%BE%AA%E7%8E%AF"><span class="nav-number">1.</span> <span class="nav-text">事件循环</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%95%BF%E6%97%B6%E4%BB%BB%E5%8A%A1"><span class="nav-number">2.</span> <span class="nav-text">长时任务</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#perform-long-operation%EF%BC%88%E6%8E%A8%E8%8D%90%EF%BC%89"><span class="nav-number">2.1.</span> <span class="nav-text">perform_long_operation（推荐）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%81%B7%E6%87%92%E5%86%99%E6%B3%95%EF%BC%88%E4%B8%8D%E6%8E%A8%E8%8D%90%EF%BC%89"><span class="nav-number">2.2.</span> <span class="nav-text">偷懒写法（不推荐）</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%9B%E5%BA%A6%E6%9D%A1"><span class="nav-number">3.</span> <span class="nav-text">进度条</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">xudonglei</p>
  <div class="site-description" itemprop="description">搬砖 嵌入式</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">283</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">67</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">xudonglei</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://muse.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'BT0Qw9HcTpPv1a6cT1iDBXKz-gzGzoHsz',
      appKey     : 'LMCMh8v02JTMFAwKNRcgoizI',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-CN' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
